import {AfterViewInit, Component, ComponentFactoryResolver, ComponentRef, Input, OnDestroy, OnInit, ViewChild, ViewContainerRef, ViewEncapsulation} from '@angular/core';
import {FieldDefinition} from "./field.definition";
import {Config, Default, Field} from "./field.model";

@Component({
  selector: 'ss-platform-field',
  templateUrl: 'field.component.html',
  styleUrls: ["field.component.scss"],
  encapsulation: ViewEncapsulation.None
})
export class FieldComponent implements OnDestroy, OnInit, AfterViewInit {

  // 容器
  @ViewChild("containerRef", {read: ViewContainerRef, static: true})
  containerRef: ViewContainerRef;
  // 组件类型
  @Input("ss-edit-title")
  isEditTitle: boolean = false;
  // 组件类型
  @Input("ss-type")
  type: string = "text";
  // 组件模型
  @Input("ss-model")
  model: Field = new Field();


  fieldDefinition = FieldDefinition;

  // 加载的组件实例
  private componentRef: ComponentRef<any>;

  constructor(private resolver: ComponentFactoryResolver) {
  }

  ngOnInit(): void {
    if (!this.model.config) {
      this.model.config = new Config();
    }
    if (!this.model.default) {
      this.model.default = new Default();
    }
  }

  loadComponent(): void {
    if (this.componentRef) {
      this.componentRef.destroy();
    }
    this.componentRef = this.containerRef.createComponent(this.resolver.resolveComponentFactory(FieldDefinition[this.type].component));
    this.componentRef.instance.model = this.model;
  }

  ngAfterViewInit(): void {
    //创建组件
    setTimeout(() => this.loadComponent(), 0);
  }

  ngOnDestroy() {
    if (this.componentRef) {
      this.componentRef.destroy();
    }
  }

}
